package au.com.bluelink.scjp.chap6;

import java.io.*;

public class FileTest {

	public static void main(String[] args) {
		
		// fell free to delete all the files created from previous runs first
		System.out.println("testing Writer1...");
		Writer1.test();
		
		System.out.println("testing Writer2...");
		Writer2.test();
		
		System.out.println("testing Writer3...");
		Writer3.test();
		
		System.out.println("testing Writer4...");
		Writer4.test();
	}

}

// The Java 5 exam focuses on
// classes from java.io
class Writer1 {
	public static void test() {
		File file = new File("fileWrite1.txt"); // There's no
		// file yet!
	}
}

class Writer2 {
	public static void test() {
		try { // warning: exceptions possible
			boolean newFile = false;
			File file = new File // it's only an object
			("fileWrite2.txt");
			System.out.println(file.exists()); // look for a real file
			newFile = file.createNewFile(); // maybe create a file!
			System.out.println(newFile); // already there?
			System.out.println(file.exists()); // look again
		} catch (IOException e) {

			System.err.println("Caught an IOException " + e.getMessage());

		}
	}
}

class Writer3 {
	public static void test() {
		char[] in = new char[50]; // to store input
		int size = 0;
		try {
			File file = new File( // just an object
					"fileWrite3.txt");
			FileWriter fw = new FileWriter(file); // create an actual file
			// & a FileWriter obj
			fw.write("howdy\nfolks\n"); // write characters to
			// the file
			fw.flush(); // flush before closing
			fw.close(); // close file when done

			FileReader fr = new FileReader(file); // create a FileReader
			// object
			size = fr.read(in); // read the whole file!
			System.out.print(size + " "); // how many bytes read
			for (char c : in)
				// print the array
				System.out.print(c);
			System.out.println();
			fr.close(); // again, always close
		} catch (IOException e) {
		}
	}
}


class Writer4 {
	public static void test() {
		char[] in = new char[50]; // to store input
		int size = 0;
		try {
			File file = new File("fileWrite4.txt");
			FileWriter fw = new FileWriter(file); 	

			// testing PrintWriter
			PrintWriter pw = new PrintWriter(fw);
			pw.println("howdy"); // write the data
			pw.println("folks");
			
			// testing BufferedWriter
			BufferedWriter bf = new BufferedWriter(fw);
			bf.write("a string");
			bf.newLine();
			
			bf.flush();
			bf.close();
			
			// testing BufferedReader
			FileReader fr = new FileReader(file);
			BufferedReader br = new BufferedReader(fr);
			System.out.println("The files length (" + file.getAbsoluteFile() + "): " + file.length() + " bytes");
			
			String line = new String();
			
			while((line = br.readLine()) != null) {
				System.out.println(line);
			}
			
		} catch (IOException e) {
		}
	}
}

